
import 'dart:convert';
import 'package:jd_shopping/HttpRequest/SpUtils.dart';
import 'package:jd_shopping/HttpRequest/configDomain.dart';


class CartServices {

  
  static addCart(item) async{
    //把对象转换成Map类型的数据
    item=CartServices.formatCartData(item);

    print(item);

//     {_id: 5a0425bc010e711234661439, title: 磨砂牛皮男休闲鞋-有属性, price: 688, selectedAttr: 牛皮 ,系带,黄色, count: 3, pic: public\upload\RinsvExKu7Ed-oc
// s_7W1DxYO.png, checked: true}

 try {
        List cartListData = json.decode(await SpUtils.get('cartList'));

        //判断购物车有没有当前数据
        bool hasData=cartListData.any((value){         
          return value['_id']==item['_id'] && value['selectedAttr']==item['selectedAttr'];
        });

        if(hasData){
          for(var i=0;i<cartListData.length;i++){
            if(cartListData[i]['_id']==item['_id']&&cartListData[i]['selectedAttr']==item['selectedAttr']){

                cartListData[i]["count"]=cartListData[i]["count"]+1;
            }
          }
          await SpUtils.save('cartList', json.encode(cartListData));

        }else{
          cartListData.add(item);
          await SpUtils.save('cartList', json.encode(cartListData));
        }


      } catch (e) {
          List tempList=[];
          tempList.add(item);
          await SpUtils.save('cartList', json.encode(tempList));
      }


    
  }

  //过滤数据
  static formatCartData(item){

     //处理图片
    String pic = item.pic;
    pic = ConfigDomian.domain +'/'+ pic.replaceAll('\\', '/');
    final Map data = new Map<String, dynamic>();
    data['_id'] = item.sId;
    data['title'] = item.title;
    data['selectedAttr'] = item.selectedAttr;
    data['count'] = item.count;
    //处理 string 和int类型的价格
    if(item.price is int || item.price is double){
        data['price'] = item.price;
    }else{
        data['price'] = double.parse(item.price);
    }   
    data['pic'] = pic;
    //是否选中
    data['checked'] = true;    
    return data;
  }


}